import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:xinxuan/common/appbar_util.dart';
import 'package:get/get.dart';
import 'package:xinxuan/common/button_util.dart';
import 'package:xinxuan/common/dialogs/del_dialog.dart';
import 'package:xinxuan/common/goods_order_info_item.dart';
import 'package:xinxuan/common/network_image_util.dart';
import 'package:xinxuan/common/scroll_configuration_common.dart';
import 'package:xinxuan/config/app_config.dart';
import 'package:xinxuan/controllers/my_controller/blind_box_order_controller/blind_box_order_detail_page_controller.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:xinxuan/utils/color_util.dart';
import 'package:xinxuan/views/my/blindBox_order/blind_box_order_btns.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:common_utils/common_utils.dart';

class BlindBoxOrderDetailPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return GetBuilder<BlindBoxOrderDetailPageController>(
      init: BlindBoxOrderDetailPageController(),
      builder: (controller) {
        return Scaffold(
          backgroundColor: pageBgColor,
          appBar: AppBarUtil(
            title: controller.appBarTitle.value,
            backgroundColor: pageBgColor,
          ),
          body: controller.orderDetailData.value.id! <= 0 ? Container() : ScrollConfigurationCommon(child: ListView(
            children: [
              Container(
                color: bgWhiteColor,
                child: Column(
                  children: [
                    Container(
                      height: 44.h,
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      alignment: Alignment.center,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            '商品信息',
                            style: TextStyle(
                              color: textBlackColor,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.bold
                            ),
                          ),
                          Text(
                            '${controller.orderDetailData.value.statusStr}',
                            style: TextStyle(
                              color: mainTextColor,
                              fontSize: 14.sp
                            ),
                          )
                        ],
                      ),
                    ),
                    _goodsInfo(
                      title: '${controller.orderDetailData.value.lottery!.product!.title}', 
                      headImage: '${controller.orderDetailData.value.lottery!.product!.image}', 
                      quantity: 1
                    ),
                    !TextUtil.isEmpty(controller.orderDetailData.value.voucherCode) ? Container(
                      width: 375.w,
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      decoration: BoxDecoration(
                        border: Border(
                          top: BorderSide(
                            color: lineColor,
                            width: .5
                          )
                        )
                      ),
                      child: Column(
                        children: [
                          Stack(
                            children: [
                              Container(
                                width: 230.w,
                                padding: EdgeInsets.symmetric(vertical: 8.h),
                                alignment: Alignment.center,
                                child: Opacity(
                                  opacity: controller.orderDetailData.value.status == 8 ? .3 : 1,
                                  child: QrImage(
                                    data: controller.orderDetailData.value.writeoffUrl ?? AppConfig.shareWebPage,
                                    size: 150.w,
                                    padding: EdgeInsets.zero,
                                  )
                                )
                              ),
                              Positioned(
                                top: 0,
                                right: 0,
                                child: controller.orderDetailData.value.status == 8 ?  Image.asset(
                                  'assets/icons/icon_written_off.png',
                                  width: 72.w,
                                  height: 72.w,
                                ) : Container()
                              )
                            ],
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 8.h),
                            padding: EdgeInsets.all(6.w),
                            decoration: BoxDecoration(
                              color: controller.orderDetailData.value.status == 8 ? pageBgColor : mainTextColor_10,
                              borderRadius: BorderRadius.circular(5.w)
                            ),
                            child: Text.rich(
                              TextSpan(
                                text: '取货劵码：',
                                style: TextStyle(
                                  color: controller.orderDetailData.value.status == 8 ? textSubtitleColor : mainTextColor,
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.bold
                                ),
                                children: [
                                  TextSpan(
                                    text: '${controller.orderDetailData.value.voucherCode}',
                                    style: TextStyle(
                                      color: controller.orderDetailData.value.status == 8 ? textSubtitleColor : mainTextColor,
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.normal
                                    ),
                                  )
                                ]
                              )
                            ),
                          )
                        ],
                      ),
                    ) : Container()
                  ],
                ),
              ),
              SizedBox(height: 12.h),
              Container(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                color: bgWhiteColor,
                child: Column(
                  children: [
                    GoodsOrderInfoItem(title: '订单编号', value: '${controller.orderDetailData.value.orderSn}', showCopy: true),
                    GoodsOrderInfoItem(title: '创建时间', value: '${controller.orderDetailData.value.createdAt}'),
                  ],
                ),
              ),
              SizedBox(height: 12.h),
              Container(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                color: bgWhiteColor,
                child: Column(
                  children: controller.orderDetailData.value.costs!.map((item) {
                    return GoodsOrderInfoItem(title: '${item.label}', value: '${item.value}', color: '${item.color}');
                  }).toList(),
                ),
              ),
              controller.orderDetailData.value.transfer != null && controller.orderDetailData.value.transfer!.length > 0 ? Container(
                color: bgWhiteColor,
                margin: EdgeInsets.only(top: 12.h),
                padding: EdgeInsets.symmetric(vertical: 8.h),
                child: Column(
                  children: controller.orderDetailData.value.transfer!.map((item) {
                    return GoodsOrderInfoItem(
                      title: '${item.label}', 
                      value: '${item.value}'
                    );
                  }).toList(),
                ),
              ) : Container(),
            ],
          )),
          bottomNavigationBar: BottomAppBar(
            elevation: 0,
            child: Container(
              height: 56.h,
              alignment: Alignment.centerRight,
              padding: EdgeInsets.symmetric(horizontal: 12.w),
              child: controller.orderDetailData.value.status == 2 && TextUtil.isEmpty(controller.orderDetailData.value.voucherCode) ? BlindBoxOrderBtns(
                voucherCode: controller.orderDetailData.value.voucherCode ?? '', 
                status: controller.orderDetailData.value.status!, 
                conversionPickingFun: () {
                  List<Map<String, dynamic>> mapArr = [{
                      'image': controller.orderDetailData.value.lottery!.product!.image,
                      'title': controller.orderDetailData.value.lottery!.product!.title,
                      'price': controller.orderDetailData.value.totalAmount,
                      'quantity': 1
                  }];
                  Get.dialog(DelDialog(
                    title: '转提货',
                    message: '转提货后，商品由接受人进行提货，本人不可对订单进行操作，确认吗？', 
                    onTap: () {
                      Get.toNamed(
                        '${AppRouters.COMMON_PAGE}${AppRouters.BLINDBOX_ORDER_PAGE}${AppRouters.CONVERSION_PICKING_PAGE}',
                        arguments: {
                          'orderId': controller.orderId.value,
                          'products': mapArr,
                          'status': controller.orderDetailData.value.status!,
                          'statusStr': controller.orderDetailData.value.statusStr,
                        }
                      )!.then((res) {
                        if (res != null && res) {
                          controller.getBlindBoxOrderDetail(showLoading: false);
                        }
                      });
                    }
                  ));
                },
                pickUpCodeFun: () {
                  List<Map<String, dynamic>> mapArr = [{
                      'image': controller.orderDetailData.value.lottery!.product!.image,
                      'title': controller.orderDetailData.value.lottery!.product!.title,
                      'price': controller.orderDetailData.value.totalAmount,
                      'quantity': 1
                  }];
                  Get.dialog(DelDialog(
                    title: '获取提货券码',
                    message: '获取提货券码后，不可以再转给别人提货了，确认要生成提货券码吗？', 
                    onTap: () {
                      Get.toNamed(
                        '${AppRouters.COMMON_PAGE}${AppRouters.BLINDBOX_ORDER_PAGE}${AppRouters.PICKUP_CODE_PAGE}',
                        arguments: {
                          'orderId': controller.orderId.value,
                          'products': mapArr,
                          'status': controller.orderDetailData.value.status!,
                          'statusStr': controller.orderDetailData.value.statusStr ?? '',
                        }
                      )!.then((res) {
                        if (res != null && res) {
                          controller.getBlindBoxOrderDetail(showLoading: false);
                        }
                      });
                    }
                  ));
                },
                seePickUpCodeFun: () {},
                isWriteoffOfficer: controller.commonPageController.userData.value.isWriteoffOfficer ?? 0,
                type: controller.orderDetailData.value.type ?? 0,
                checkoff: () async {
                  await controller.blindBoxOrderPageController.checkoff(controller.orderDetailData.value.id!);
                  controller.getBlindBoxOrderDetail();
                }, 
              ) : ButtonUtil(
                text: '在线客服', 
                fontSize: 14.sp, 
                borderRadius: 18.w, 
                height: 36.h, 
                onTop: () {
                  controller.commonPageController.openWeChatCustomerServiceChat();
                }
              ),
            ),
          ),
        );
      },
    );
  }

  /// 商品信息
  Widget _goodsInfo({ required String title, required String headImage, required int quantity,}) {
    return Container(
      padding: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 12.h),
      color: bgWhiteColor,
      child: Row(
        children: [
          NetworkImageUtil(
            url: headImage, 
            width: 90.w, 
            height: 90.w,
            borderRadius: 5.w,
          ),
          SizedBox(width: 12.w),
          Expanded(child: Container(
            constraints: BoxConstraints(
              minHeight: 90.w
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 2,
                  style: TextStyle(
                    color: textBlackColor,
                    fontSize: 14.sp
                  ),
                ),
                SizedBox(height: 6.h),
                Text(
                  'x$quantity',
                  style: TextStyle(
                    color: textSubtitleColor,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.bold
                  )
                ),
              ],
            ),
          )),
        ],
      ),
    );
  }
}